﻿using Server.Manager;
using Server.Struct;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.DTool
{
    class BufferManager
    {
        readonly static byte[] EmptyBuffer = new byte[1] { 0 };
        readonly int _capcity;
        readonly int _bufferSize;
        readonly int _bufferCount;

        readonly byte[] _buffer;

        readonly Stack<int> _emptyOffsets;

        public BufferManager(int bufferCount, int bufferSize)
        {
            _capcity = bufferCount * bufferSize;
            _bufferSize = bufferSize;
            _bufferCount = bufferCount;

            _buffer = new byte[_capcity];

            _emptyOffsets = new Stack<int>(_bufferCount);

            for (int i = 0; i < _bufferCount; i++)
            {
                _emptyOffsets.Push(i * bufferSize);
            }
        }

        public void SetBuffer(IBufferSegment seg)
        {
            if (_emptyOffsets.Count < 1)
                throw new ArgumentOutOfRangeException("没有足够空间分配");

            seg.SetBuffer(_buffer, _emptyOffsets.Pop(), _bufferSize);
        }

        public void RecycleBuffer(IBufferSegment seg)
        {
            _emptyOffsets.Push(seg.Offset);
        }
    }
}
